package org.kjtc.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.kjtc.entity.ChargingStationStatus;
import org.kjtc.entity.ChargingStationUpgrade;
import org.kjtc.entity.DeviceObject;
import org.kjtc.entity.Page;
import org.kjtc.service.ActionHistoryService;
import org.kjtc.service.ChargingStationService;
import org.kjtc.util.Const;
import org.kjtc.util.FileUpload;
import org.kjtc.util.FileUtil;
import org.kjtc.util.PathUtil;
import org.kjtc.util.Tools;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class ChargingStationUpgradeController extends BaseController {

	@Resource(name = "chargingStationService")
	private ChargingStationService chargingStationService;

	@Resource(name = "actionHistoryService")
    private ActionHistoryService actionHistoryService;

	@Resource(name = "deviceObject")
    private DeviceObject deviceObject;

	Map<String, Object> subStationMap = null;
	Map<String, Object> upgradeMap = null;
	String userID = null;

	@ResponseBody
	@RequestMapping(value = "/upgrade/request")
	public Object getSubStationRequest(HttpServletRequest request, @RequestBody String requestBody) {

		Map<String, Object> map = new HashMap<String, Object>();
		Date requestDTTM = new Date();
		try {
			logger.info("充电站升级访问信息：【IP：" + Tools.getIPAddress(request) + ", 主机名" + request.getRemoteHost() + ", 端口" + request.getRemotePort() + "】");
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		JSONObject upgradeJson = JSONObject.fromObject(requestBody);
		logger.info("充电站升级请求数据：" + upgradeJson);
		if (upgradeJson != null && upgradeJson.has("chargingStationID")) {
			String chargingStationID = upgradeJson.getString("chargingStationID");
			upgradeMap = deviceObject.getUpgradeMap();
			if (upgradeMap == null) {
				upgradeMap = new HashMap<String, Object>();
			}
			ChargingStationUpgrade chargingStationUpgrade = null;
			chargingStationUpgrade = (ChargingStationUpgrade)upgradeMap.get(chargingStationID);
			subStationMap = deviceObject.getSubStationMap();
			ChargingStationStatus chargingStationStatus = null;
			chargingStationStatus = (ChargingStationStatus)subStationMap.get(chargingStationID);
			if ("START".equals(chargingStationStatus.getUpgradeStatus())) {
				String downloadFile = chargingStationStatus.getUpgradeFile();
				map.put("downloadFile", downloadFile);
				map.put("downloadUrl", PathUtil.PathAddress() + Const.SUBSTATION_DOWNLOAD_URL);
				logger.info("云平台命令充电站【" + chargingStationStatus.getChargingStationID() + "】开始下载升级文件" + downloadFile);
				logger.info("云平台下载路径：" + map.get("downloadUrl"));
			}
			if (upgradeJson.has("upgradeStatus")) {
				if ("END".equals(upgradeJson.getString("upgradeStatus"))) {
					logger.info("子站升级下载成功");
					chargingStationStatus.setUpgradeStatus("END");
					chargingStationUpgrade = new ChargingStationUpgrade();
					chargingStationUpgrade.setChargingStationID(chargingStationID);
					chargingStationUpgrade.setCurrentVersion(chargingStationStatus.getCurrentVersion());
					chargingStationUpgrade.setUpgradeVersion(chargingStationStatus.getUpgradeVersion());
					chargingStationUpgrade.setUpgradeFile(chargingStationStatus.getUpgradeFile());
					chargingStationUpgrade.setCreateUser(chargingStationStatus.getUpgradeUser());
					chargingStationUpgrade.setUpdateUser(chargingStationStatus.getUpgradeUser());
					Date now = new Date();
					chargingStationUpgrade.setCreateDTTM(now);
					chargingStationUpgrade.setUpdateDTTM(now);
					now = null;
					map.remove("downloadFile");
					map.remove("downloadUrl");
					try {
						chargingStationService.saveChargingStationUpgrade(chargingStationUpgrade);
					} catch (Exception e) {
						e.printStackTrace();
						logger.error("子站站升级记录保存异常：" + e.getMessage());
					}
				} else if ("TIMEOUT".equals(upgradeJson.getString("upgradeStatus"))) {
					chargingStationStatus.setUpgradeStatus("TIMEOUT");
					logger.info("子站升级超时");
				} else if ("ERROR".equals(upgradeJson.getString("upgradeStatus"))) {
					chargingStationStatus.setUpgradeStatus("ERROR");
					logger.info("子站升级异常");
				} else {
					chargingStationStatus.setUpgradeStatus("WAIT");
				}
			}
			map.put("result", "Success");
		} else {
			logger.error("充电站升级请求数据没有项目'chargingStationID'");
			map.put("result", "AccessForbidden");
		}

		String jsonResult = JSONObject.fromObject(map).toString();
		logger.info("云平台接收子站实时状态返回数据：" + jsonResult);
		map = null;
		return jsonResult;
	}
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/getRealTimeUpgradeStatus")
	public Object getUpgradeStatus(String chargingStationID) throws InterruptedException {

		Map<String, Object> map = new HashMap<String, Object>();
		List<ChargingStationUpgrade> chargingStationUpgradeList = (List<ChargingStationUpgrade>)this.getSession().getAttribute("chargingStationUpgradeList");
		subStationMap = deviceObject.getSubStationMap();
		for (ChargingStationUpgrade csu : chargingStationUpgradeList) {
			chargingStationID = csu.getChargingStationID();
			if (subStationMap != null && subStationMap.containsKey(chargingStationID)){
				ChargingStationStatus chargingStationStatus = (ChargingStationStatus)subStationMap.get(csu.getChargingStationID());
				Date requestDTTM = chargingStationStatus.getRequestDTTM();
				if (requestDTTM != null) {
					Date now = new Date();
					long second = (now.getTime() - requestDTTM.getTime()) / 1000;
					if (second < Const.SUBSTATION_OUTLINETIME) {
						csu.setOnlineStatus(true);
						csu.setCurrentVersion(chargingStationStatus.getCurrentVersion());
						csu.setUpgradeStatus(chargingStationStatus.getUpgradeStatus());
						File file = new File(Const.UPGRADE_PATH);
						if (file.exists()) {
							File[] files = file.listFiles();
							List<String> upgradeFileList = new ArrayList<String>();
							for (File upgradeFile : files) {
								upgradeFileList.add(upgradeFile.getName());
							}
							csu.setUpgradeFileList(upgradeFileList);
						}
					} else {
						csu.setUpgradeFileList(null);
						csu.setOnlineStatus(false);
						csu.setUpgradeStatus(null);
						csu.setCurrentVersion(null);
						subStationMap.remove(chargingStationID);
					}
				}
			}
		}
		map.put("chargingStationUpgradeList", chargingStationUpgradeList);
		return map;
	}

	@ResponseBody
	@RequestMapping(value = "/chargingStationUpgrade")
	public Object upgrade(String chargingStationID, String downloadFile, String upgradeVersion) {

		Map<String, Object> map = new HashMap<String, Object>();
		userID = this.getUesr().getUserID();
		subStationMap = deviceObject.getSubStationMap();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + this.getClass().getClassLoader().getResource(".").getPath());
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + Thread.currentThread().getContextClassLoader().getResource(".").getPath());
		if (subStationMap != null && subStationMap.containsKey(chargingStationID)){
			ChargingStationStatus chargingStationStatus = (ChargingStationStatus)subStationMap.get(chargingStationID);
			logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "服务器指令子站-" + chargingStationStatus.getChargingStationName() + "升级");
			if (null != downloadFile && !"".equals(downloadFile)) {
				chargingStationStatus.setUpgradeFile(downloadFile);
				chargingStationStatus.setUpgradeVersion(upgradeVersion);
				chargingStationStatus.setUpgradeStatus("START");
				chargingStationStatus.setUpgradeUser(userID);
				map.put("result", "Sucess");
				logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "升级文件：" + downloadFile);
				actionHistoryService.saveActionHistory(userID, "服务器指令子站升级");
			} else {
				chargingStationStatus.setUpgradeFile(null);
				chargingStationStatus.setUpgradeVersion(null);
				map.put("result", "NotExist");
				logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "升级文件不存在！");
			}
		} else {
			map.put("result", "Offline");
			logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "子站通讯断开，无法升级！");
		}
		return map;
	}

	@ResponseBody
	@RequestMapping(value = "/subStation/download")
	public void download(@RequestBody String requestBody, HttpServletResponse response) {
		try {
			JSONObject json = JSONObject.fromObject(requestBody);
			JSONObject jsonObject = Tools.getJsonData(json, "realTimeData", "");
			logger.info("子站下载升级文件开始，请求数据：" + jsonObject);
			actionHistoryService.saveActionHistory(userID, "子站下载升级文件开始");
			String filePath = "";
			String fileName = "";
			if (jsonObject.has("chargingStationID")) {
				String chargingStationID = jsonObject.getString("chargingStationID");
				subStationMap = deviceObject.getSubStationMap();
				if (subStationMap != null && subStationMap.containsKey(chargingStationID)){
					ChargingStationStatus chargingStationStatus = (ChargingStationStatus)subStationMap.get(chargingStationID);
					filePath = Const.UPGRADE_PATH + chargingStationStatus.getUpgradeFile();
					fileName = chargingStationStatus.getUpgradeFile();
					logger.info("子站-" + chargingStationStatus.getChargingStationName() + "，下载升级文件：" + fileName);
					if (fileName != null && !"".equals(fileName)) {
						File file = new File(filePath);
						if (file.exists()) {
							byte[] data = FileUtil.toByteArray2(filePath);
						    fileName = URLEncoder.encode(fileName, "UTF-8");
						    response.reset();
						    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
						    response.addHeader("Content-Length", "" + data.length);
						    response.setContentType("application/octet-stream;charset=UTF-8");
						    OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
						    outputStream.write(data);
						    outputStream.flush();
						    outputStream.close();
						    response.flushBuffer();
						    outputStream = null;
						    logger.error("子站下载升级文件完成");
						    actionHistoryService.saveActionHistory(userID, "子站下载升级文件完成");
						} else {
							logger.error("子站升级失败，服务器找不到升级文件：" + filePath);
							actionHistoryService.saveActionHistory(userID, "子站升级失败，服务器找不到升级文件：" + filePath);
						}
					} else {
						logger.error("子站升级失败，升级文件名不能为空");
						actionHistoryService.saveActionHistory(userID, "子站升级失败，升级文件名不能为空");
					}
				} else {
					logger.error("子站升级失败，服务器内存map中找不到升级充电站ID！");
					actionHistoryService.saveActionHistory(userID, "子站升级失败，服务器内存map中找不到升级充电站ID！");
				}
			} else {
				logger.error("子站升级失败，请求数据中找不到key：'chargingStationID'");
				actionHistoryService.saveActionHistory(userID, "子站升级失败，请求数据中找不到key：'chargingStationID'");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("子站下载升级文件异常:" + e.getMessage());
			actionHistoryService.saveActionHistory(userID, "子站下载升级文件异常:" + e.getMessage());
		}
		actionHistoryService.saveActionHistory(userID, "子站下载升级文件结束");
		logger.info("子站下载升级文件结束");
	}

	@ResponseBody
	@RequestMapping(value = "/uploadUpgradeFile")
	public Object uploadUpgradeFile(@RequestParam(value="upgradeFile", required=false) MultipartFile file) {

		Map<String, Object> map = new HashMap<String, Object>();
		if (file != null && !file.isEmpty()) {
			String filePath = Const.UPGRADE_PATH;
			String fileName = null;
			try {
				fileName = FileUpload.uploadFile(file.getInputStream(), filePath, file.getOriginalFilename());
				map.put("result", "Sucess");
			} catch (IOException e) {
				map.put("result", "Error");
				logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "升级文件【" + file.getOriginalFilename() + "】上传异常:" + e.getMessage());
			}

			actionHistoryService.saveActionHistory(this.getUesr().getUserID(), "更新文件" + file.getOriginalFilename() + "已成功上传到" + filePath + fileName);
			logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "升级文件【" + file.getOriginalFilename() + "】成功上传到" + filePath + fileName);
		} else {
			map.put("result", "NotFound");
		}
		return map;
	}

	@ResponseBody
	@RequestMapping(value = "/searchChargingStationUpgrade")
	public Object getChargingStationUpgrade(ChargingStationUpgrade chargingStationUpgrade, String page, String rows) {

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电站升级信息查询开始");
		subStationMap = deviceObject.getSubStationMap();
		// 分页
		Page pageQuery = getPage();
		pageQuery.setCurrentPage(Integer.parseInt(page));
		pageQuery.setCurrentResult((Integer.parseInt(page) - 1) * (Integer.parseInt(rows)));
		pageQuery.setShowCount(Integer.parseInt(rows));

		try {
			List<ChargingStationUpgrade> chargingStationUpgradeList = chargingStationService.getChargingStationUpgradePage(chargingStationUpgrade, pageQuery);
			String currentVersion = "";
			String chargingStationID = "";
			for (ChargingStationUpgrade csu : chargingStationUpgradeList) {
				chargingStationID = csu.getChargingStationID();
				if (subStationMap != null && subStationMap.containsKey(chargingStationID)){
					ChargingStationStatus chargingStationStatus = (ChargingStationStatus)subStationMap.get(csu.getChargingStationID());
					// 升级前版本
					Date requestDTTM = chargingStationStatus.getRequestDTTM();
					if (requestDTTM != null) {
						Date now = new Date();
						long second = (now.getTime() - requestDTTM.getTime()) / 1000;
						if (second < Const.SUBSTATION_OUTLINETIME) {
							csu.setOnlineStatus(true);
							currentVersion = chargingStationStatus.getCurrentVersion();
							if (null != currentVersion && !"".equals(currentVersion)) {
								csu.setCurrentVersion(currentVersion);
							}
							chargingStationStatus.setUpgradeStatus(null);
							File file = new File(Const.UPGRADE_PATH);
							if (file.exists()) {
								File[] files = file.listFiles();
								List<String> upgradeFileList = new ArrayList<String>();
								for (File upgradeFile : files) {
									upgradeFileList.add(upgradeFile.getName());
								}
								csu.setUpgradeFileList(upgradeFileList);
							}
						} else {
							csu.setUpgradeFileList(null);
							subStationMap.remove(chargingStationID);
						}
					}
				}
			}
			this.getSession().setAttribute("chargingStationUpgradeList", chargingStationUpgradeList);
			map.put("totalCnt", pageQuery.getTotalResult());
			map.put("totalPage", pageQuery.getTotalPage());
			map.put("chargingStationUpgradeList", chargingStationUpgradeList);
			map.put("result", "Sucess");
		} catch (Exception e) {
			map.put("result", "Error");
			logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电站升级信息查询异常:" + e.getMessage());
		}
		actionHistoryService.saveActionHistory(this.getUesr().getUserID(), "充电站升级信息查询");
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电站升级信息查询结束");
		return map;
	}
}